package com.spontaneappnew.activities;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.spontaneappnew.Categories_Places;
import com.spontaneappnew.Category;
import com.spontaneappnew.NavDrawerActivityConfiguration;
import com.spontaneappnew.NavDrawerItem;
import com.spontaneappnew.NavMenuFBHeader;
import com.spontaneappnew.NavMenuItem;
import com.spontaneappnew.Place;
import com.spontaneappnew.Places;
import com.spontaneappnew.R;
import com.spontaneappnew.adapters.NavDrawerAdapter;

public class FilteredPlacesActivity extends AbstractNavDrawerActivity {
	
	private ExpandableListAdapter adapter;
	private ExpandableListView lv;
	
	private double lat,lng;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		lv = (ExpandableListView)findViewById(R.id.filtered_places_list);
		
		if (Places.getInstance().getFilteredCategories().size()==0){
			Toast.makeText(this, "There are no places in the categories you have selected.", Toast.LENGTH_SHORT).show();
			finish();
		}
		
		// bundle is used to calculate distance between user's location and the filtered places
		Bundle bundle = getIntent().getExtras();
		if(bundle != null){
			lat = bundle.getDouble("lat", 0);
			lng = bundle.getDouble("lng", 0);
		}
		
		adapter = new FilteredListAdapter(this,Places.getInstance().getFilteredPlaces(),Places.getInstance().getFilteredCategories());
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		lv.setAdapter(adapter);
		lv.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				Places.getInstance().setCurrentPlace(groupPosition, childPosition, 4);
				Intent i = new Intent(FilteredPlacesActivity.this,PlaceProfileActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
				return false;
			}
		});
		int numOfGroups = Places.getInstance().getFilteredCategories().size();
		for (int i=0; i<numOfGroups;i++)
			lv.expandGroup(i);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.filtered_places, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_choose_categories_map_view){
				Intent intent = new Intent(FilteredPlacesActivity.this,MapActivity.class);
				intent.putExtra("FilteredView", 1);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
				return true;
		} else 
				return super.onOptionsItemSelected(item);
	}
	
////////////////////////////// Expandable List Adapter	///////////////////////////////////////////////////////////////////////
	
	private class FilteredListAdapter extends BaseExpandableListAdapter {
		
		private LayoutInflater li;
		private ArrayList<Categories_Places> placesList;
		private ArrayList<Category> categoriesList;
		private String kmOrMile;
		
		public FilteredListAdapter(Context context, ArrayList<Categories_Places> PList , ArrayList<Category> cateList){
			   this.placesList = PList;
			   this.categoriesList=cateList;
			   this.li = LayoutInflater.from(context);
			   kmOrMile = getKMOrMile();
		}
		
		@Override
		public Place getChild(int groupPosition, int childPosition) {
			return this.placesList.get(groupPosition).getPlaceList().get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, final int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {
			final Place childText = (Place) getChild(groupPosition, childPosition);
			if (convertView == null) {
				convertView = li.inflate(R.layout.filtered_list_row, null);
			}
			TextView name = (TextView) convertView.findViewById(R.id.filtered_list_row_place_name);
			name.setText(childText.getName());
			TextView address = (TextView) convertView.findViewById(R.id.filtered_list_row_place_address);
			address.setText(childText.getStreet());
			TextView distance = (TextView) convertView.findViewById(R.id.filtered_list_row_place_distance);
			
			distance.setText(""+ getDistance(childText.getLocation().getLatitude(), 
					childText.getLocation().getLongitude()) + kmOrMile);
			RatingBar rating  = (RatingBar) convertView.findViewById(R.id.filtered_list_row_place_rating);
			rating.setRating(childText.getRating());
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return this.placesList.get(groupPosition).getPlaceList().size();
		}

		@Override
		public Category getGroup(int groupPosition) {
			return this.categoriesList.get(groupPosition);
		}
		
		@Override
		public int getGroupCount() {
			return this.categoriesList.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {
			String headerTitle = getGroup(groupPosition).getName();
			if (convertView == null) {
					convertView = li.inflate(R.layout.filtered_list_header, null);
			}
		    TextView headerName = (TextView) convertView.findViewById(R.id.filtered_list_header_title);
		    headerName.setTypeface(null, Typeface.BOLD);
		    headerName.setText(headerTitle);

		    return convertView;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
		
		/*
		 * get km or miles from shared preferences!
		 */
		private String getKMOrMile(){
			if(getSharedPreferences("PREF",0).getBoolean("isKm", true))
				return " km";
			else
				return " Miles";
		}
		
		/*
		 * Calculate distance (check for miles or km)
		 */
		private double getDistance(double placeLat, double placeLng){
			double dist = calculateDistanceFromCurrentLocationInMiles(placeLat, placeLng);
			if(getSharedPreferences("PREF",0).getBoolean("isKm", true)){
				double meterConversion = 1.6;
				dist *= meterConversion;
			}
			return Math.floor(dist * 10) / 10;
		}
		
		/*
		 * Function of the List Fragments interface 
		 */
		// Gets a lat and long and returns the distance from the user's current location
		public double calculateDistanceFromCurrentLocationInMiles(double placeLat, double placeLng) {
			if(lat == 0 || lng == 0){
				return 0;
			}
			else{
			    double earthRadius = 3958.75;
				double dLat = Math.toRadians(lat-placeLat);
				double dLng = Math.toRadians(lng-placeLng);
			    double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat)) * Math.cos(Math.toRadians(placeLat)) * Math.sin(dLng/2) * Math.sin(dLng/2);
			    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
			    double dist = earthRadius * c;
			    return dist;
			}
		}

	}
	
	
////////////////////// NAV DRAWER ///////////////////////////////////////////
	
	@Override
    protected void onNavItemSelected(int id) {
		Intent intent = null;
        switch ((int)id) {
        // Home nav button was pressed - no need to act
        case 101:
        	intent = new Intent(this, HomeActivity.class);
            break;
        // My places nav drawer was pressed
        case 102:
        	intent = new Intent(this, MyPlacesNew.class);
        	break;
        // Settings nav button was pressed
        case 103:
            intent = new Intent(this, SettingsActivity.class);
            break;
	    }
        if(intent != null)
        	startActivity(intent);
        else
        	super.onNavItemSelected(id);
    }
	
	/*
     * Initialize the nav drawer configurations and returns it to navConf
     */
	@Override
    protected NavDrawerActivityConfiguration getNavDrawerConfiguration() {
        NavDrawerItem[] menu = new NavDrawerItem[] {
        		NavMenuFBHeader.create( 100, "User"),
                NavMenuItem.create(101, "Home", "ic_home", this),
                NavMenuItem.create(102, "My Places", "ic_menu_myplaces", this),
                NavMenuItem.create(103, "Settings", "ic_menu_settings", this),
                NavMenuItem.create(105, "About", "ic_action_about_light", this),
                NavMenuItem.create(107, "Rate Us!", "ic_whats_hot", this),
                NavMenuItem.create(108, "Logout", "ic_menu_logout", this)};
        
        NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
        navDrawerActivityConfiguration.setMainLayout(R.layout.activity_filtered_places);
        navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
        navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_drawer);
        navDrawerActivityConfiguration.setNavItems(menu);
        navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);       
        navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
        navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
        navDrawerActivityConfiguration.setBaseAdapter(
            new NavDrawerAdapter(this, R.layout.navdrawer_item, menu ));
        return navDrawerActivityConfiguration;
    }
}
